<template>
  <li >
    <label>
      <input type="checkbox"
             :checked="todos.done"
             @click="handleCheck(todos.id)"/>
      <span v-show="!todos.isEdit">{{ todos.title  }}</span>
      <input
          v-show="todos.isEdit"
          type="text"
          :v-model="todos.title"
          :value="todos.title"
          @blur="handleBlur(todos,$event)"
          ref="inputTitle"
      >
    </label>
    <button class="btn btn-danger" @click="deletestr(todos.id,todos.done)">删除</button>
    <button class="btn btn-edit" v-show="!todos.isEdit" :value="todos.title" @click="handleEdit(todos)">编辑</button>
  </li>
</template>

<script>
import 'animate.css'
import pubsub from "pubsub-js";
export default {
  name: "MyItem",
  props:['todos'],
  methods:{
    handleCheck(id){
      //通知App组件对应的todo对象的done值取反
      // this.checkTodo(id);
      this.$bus.$emit('checkTodo',id)
    },
    //如果删除的时候判断选中的为false的话 将调用父组件传递过来的函数然后父组件将判断这个列表是否删除
    deletestr(id,done){
      // this.$bus.$emit('deleteObj',id,done)  //全局事件总线
      if(confirm('确定删除吗？')){
      const dd = {id:id,done:done};
      pubsub.publish('deleteObj',dd) //订阅消息
      }
    },
    //编辑
    handleEdit(todo){
      todo.isEdit = true
      //不写定时器将不进行改变，因为如果一走到这里就渲染，那么会涉及到效率
      // setTimeout(()=>{
      //   //获得焦点
      //   this.$refs.inputTitle.focus();
      // },100)

      //DOM模板全部更新之后再调用这个函数
      this.$nextTick(function (){
        this.$refs.inputTitle.focus();
      })

    },
    handleBlur(todo,e){
      todo.isEdit = false
      if(!e.target.value.trim()) return alert("输入不能为空")
      this.$bus.$emit('updateTodo',todo.id,e.target.value)
    }
  }
}
</script>


<style>

/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

</style>